package payment

import (
	"context"
	"fmt"
	"time"

	"oil-station-backend/internal/service"
	"oil-station-backend/internal/svc"
	"oil-station-backend/internal/types"
	"oil-station-backend/internal/utils"

	"github.com/zeromicro/go-zero/core/logx"
)

type CreatePaymentOrderLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewCreatePaymentOrderLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CreatePaymentOrderLogic {
	return &CreatePaymentOrderLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *CreatePaymentOrderLogic) CreatePaymentOrder(req *types.CreatePaymentOrderReq) (resp *types.CreatePaymentOrderResp, err error) {
	// 从上下文中获取用户信息
	userId, _, err := utils.GetUserInfoFromContext(l.ctx)
	if err != nil {
		return nil, err
	}

	// 获取用户信息
	user, err := l.svcCtx.UserModel.FindById(userId)
	if err != nil {
		return nil, fmt.Errorf("用户不存在")
	}

	l.Infof("创建支付订单，用户ID: %d, 金额: %d分", userId, req.Amount)

	// 生成临时支付ID
	paymentId := fmt.Sprintf("PAY%d%d", time.Now().Unix(), userId)

	// 初始化微信服务
	wechatService := service.NewWechatService()

	// 创建微信支付参数（不依赖订单ID）
	wechatPayReq := &types.WechatPayReq{
		OrderId:     0, // 临时设为0，实际使用paymentId
		Description: req.Description,
		Amount:      req.Amount,
	}

	// 创建微信支付订单
	payResp, err := wechatService.CreatePaymentWithoutOrder(wechatPayReq, user.OpenId, paymentId)
	if err != nil {
		l.Errorf("创建微信支付订单失败: %v", err)
		return nil, fmt.Errorf("创建支付订单失败")
	}

	l.Infof("支付订单创建成功，支付ID: %s, 用户ID: %d", paymentId, userId)

	return &types.CreatePaymentOrderResp{
		PaymentId: paymentId,
		TimeStamp: payResp.TimeStamp,
		NonceStr:  payResp.NonceStr,
		Package:   payResp.Package,
		SignType:  payResp.SignType,
		PaySign:   payResp.PaySign,
	}, nil
}